{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "def dir_size(d):\n",
    "    '''\n",
    "    统计指定目录大小\n",
    "    '''\n",
    "    # 初始值0\n",
    "    sum = 0\n",
    "    # 判断是否为文件\n",
    "    if os.path.isfile(d):\n",
    "        # 是文件，获取大小\n",
    "        sum += os.path.getsize(d)\n",
    "    # 判断是否为目录\n",
    "    if os.path.isdir(d):\n",
    "        # 是目录，获取目录下列表\n",
    "        dlist = os.listdir(d)\n",
    "        # 遍历列表\n",
    "        for f in dlist:\n",
    "            # 为遍历的文件添加目录路径\n",
    "            file = os.path.join(d,f)\n",
    "            if os.path.isfile(file):\n",
    "                sum += os.path.getsize(file)\n",
    "            if os.path.isdir(file):\n",
    "                sum += dir_size(file)  #递归\n",
    "    return sum\n",
    "\n",
    "while True:\n",
    "    key = input('请输入文件夹或文件的绝对路径：')\n",
    "    print('{}字节'.format(dir_size(key)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
